package com.eii.system.controller;

import com.eii.common.annotation.LoginUser;
import com.eii.common.constant.UserConstants;
import com.eii.common.model.auth.SysUser;
import com.eii.common.utils.StringUtils;
import com.eii.common.web.controller.BaseController;
import com.eii.common.web.domain.Result;
import com.eii.log.annotation.AuditLog;
import com.eii.oauth2.common.annotation.RequiresPermissions;
import com.eii.system.api.domain.SysDept;
import com.eii.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 部门信息
 */
@RestController
@RequestMapping("/dept")
public class SysDeptController extends BaseController {

    private final static String CONTROLLER_TITLE = "部门管理";

    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取部门列表
     */
    @RequiresPermissions("system:dept:list")
    @GetMapping("/list")
    public Result list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return Result.success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @RequiresPermissions("system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public Result<List<SysDept>> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext()) {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || StringUtils.equalsAny((deptId + ""), d.getAncestors().split(","))) {
                it.remove();
            }
        }
        return Result.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @RequiresPermissions("system:dept:query")
    @GetMapping(value = "/{deptId}")
    public Result getInfo(@PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return Result.success(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public Result treeselect(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return Result.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public Result<Map<String, Object>> roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        resultMap.put("depts", deptService.buildDeptTreeSelect(depts));
        return Result.success(resultMap);
    }

    /**
     * 新增部门
     */
    @RequiresPermissions("system:dept:add")
    @AuditLog(title = CONTROLLER_TITLE, operation = "'删除:' + #dept.deptId")
    @PostMapping
    public Result add(@Validated @RequestBody SysDept dept, @LoginUser SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return Result.fail("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(user.getUsername());
        return toResult(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @RequiresPermissions("system:dept:edit")
    @AuditLog(title = CONTROLLER_TITLE, operation = "'更新:' + #dept.deptId")
    @PutMapping
    public Result edit(@Validated @RequestBody SysDept dept, @LoginUser SysUser user) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return Result.fail("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return Result.fail("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return Result.fail("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(user.getUsername());
        return toResult(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @RequiresPermissions("system:dept:remove")
    @AuditLog(title = CONTROLLER_TITLE, operation = "'删除:' + #deptId")
    @DeleteMapping("/{deptId}")
    public Result remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return Result.fail("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return Result.fail("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toResult(deptService.deleteDeptById(deptId));
    }
}
